package com.chendx.store.order.netty;

import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.store.common.constants.ampq.AMQPConstants;
import com.chendx.store.common.constants.order.OrderConstants;
import com.chendx.store.order.config.ApplicationContextProvider;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by chendx on 2022/4/24.
 */
public class OrderWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static ObjectMapper MAPPER = new ObjectMapper();
    //获取WebSocket连接的map
    public static ConcurrentHashMap<String, Channel> webSocketMap = new ConcurrentHashMap<>();

    private static RabbitTemplate rabbitTemplate = ApplicationContextProvider.getApplicationContext().getBean(RabbitTemplate.class);

    private static StringRedisTemplate redisTemplate = ApplicationContextProvider.getApplicationContext().getBean(StringRedisTemplate.class);

    private SimpleMessageListenerContainer orderNoticeContainer =
            (SimpleMessageListenerContainer) ApplicationContextProvider.getApplicationContext().getBean("orderNoticeContainer");


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame message) throws Exception {

        String json = message.text();
        String username = MAPPER.readTree(json).get("username").asText();
        Channel channel = webSocketMap.get(username);

        if (channel == null){
            channel = ctx.channel();
            webSocketMap.put(username,channel);
        }
        if (channel.isActive() == false){
            channel = ctx.channel();
            webSocketMap.put(username,channel);
        }
        RabbitAdmin rabbitAdmin = new RabbitAdmin(rabbitTemplate);
        String queueName = AMQPConstants.ORDER_PAY_NOTICE+ username;
        rabbitAdmin.declareQueue(new Queue(queueName));
        Properties queueProperties = rabbitAdmin.getQueueProperties(queueName);
        int noticeCount = 0;
        if (queueProperties != null){
            //   System.out.println(JSON.toJSONString(queueProperties));
            //    System.out.println(queueProperties.get("QUEUE_MESSAGE_COUNT"));
            noticeCount = (int) queueProperties.get("QUEUE_MESSAGE_COUNT");
            redisTemplate.boundHashOps(OrderConstants.NO_READ_ORDER_NOTICE).increment(username,noticeCount);
        }
        //封装返回的数据
        HashMap countMap = new HashMap();
        countMap.put("orderNoticeCount", noticeCount);
        ResponseResult responseResult = ResponseResult.okResult(countMap);
        channel.writeAndFlush(new TextWebSocketFrame(MAPPER.writeValueAsString(responseResult)));
        if (noticeCount > 0){
            rabbitAdmin.purgeQueue(queueName,true);
        }
        orderNoticeContainer.addQueueNames(queueName);
    }
}
